<template>
    <div class="departTree-dialog">
        <formInput v-if="!showButton" :value="checkedData.name" :readonly="!useInput" :disabled="disabled" :placeholder="placeholder" search="选择" @search="searchClick" @blur="blur" :rule="rule"></formInput>
        <el-button v-if="showButton" type="primary" @click="searchClick(null)" :icon="buttonIcon">{{buttonText}}</el-button>
        <commonDialog class="departDialog" title="单位树" appendBody :visible.sync="dialogVisible" :save="save" width="600px">
            <commonTree :render="renderContent" v-if="dialogVisible" ref="commonTree"
                height="100%" autoHeight
                :lazy="isLazy" checkStrictly :multiple="multiple" :selectable="selectable?selectable:multiple"
                v-model="checkedVal" :options="treeData"
                :props="treeProps" :search="searchData"
                :nodeUrl="nodeUrl" :loadForNode="loadForNode"
                :noPermission="noPermission"
                @nodeClick="nodeClick"
                @checkedChange="checkedChange"
            >
                <formInput class="filterInput radius" v-model="searchText" suffixIcon="el-icon-search" placeholder="请输入搜索关键字" @iconClick="search()"></formInput>
            </commonTree>
            <div slot="foot">
                已选中 <span class="blue">{{selectedCount}}</span> 个单位
            </div>
            <el-button slot="more"  type="danger" @click="clear()">清空</el-button>
        </commonDialog>
    </div>
</template>

<script lang="jsx">
export default {
    name: 'departDialog',
    props:{
        label:String,
        name:String,
        value:[String,Array],
        rowData:[Object,Array],
        placeholder:{
            type:String,
            default:"请选择"
        }, showButton:{
            type:Boolean,
            default:false
        },buttonText:{
            type:String,
            default:"选择单位"
        },buttonIcon:{
            type:String,
            default:"el-icon-s-promotion"
        },
        disabled:{
            type:Boolean,
            default:false,
        },
        limit: {         //是否添加权限限制
            type: String,
            default: 'limited',
        },
        useInput:{
            type:Boolean,
            default:false,
        },
        selectable:{//->是否需要复选框
            type:Boolean,
            default:false
        },
        multiple:{
            type:Boolean,
            default:false
        },
        visible:{
            type:Boolean,
            default:false
        },
	    noPermission: {                                           //后台根据账号权限显示机构树
		    type: Boolean,
		    default: false,
	    },
        organizationType: {                                           //是否显示全部机构树
		    type: Boolean,
		    default: false,
	    },
        dataProps:{},
        rule:Object,
        openAfterBlur: {
            type: Boolean,
		    default: false,
        }
    },
    data () {
        return {
            isClear:false,
            isLazy:true,
            // inputVal:"",
            treeName:"",
            dialogVisible:false,
            // selectedCount:0,
            searchText:null,
            checkedVal:null,
            checkedData:{
              name: ''
            },
            searchData:{
                organizationId:"",
                dataOrganizationId:"",
            },
            treeProps:{
                value:"id",
                label:"name",
                children:"subTreeNode",
                isLeaf: "leaf",
                hasChildren:"hasChildren",
                isFalse: function(item){
                //by  济宁项目组
                return item.selectAble === 0
              }
            },
            treeData:[],
            nodeUrl: '',
        }
    },
    computed:{
        selectedCount() {
            console.log('===', this.checkedVal)
            // debugger
            if(this.checkedVal===null || this.checkedVal === undefined)
                return 0;
            if(typeof this.checkedVal === "string"&&this.checkedVal!=="")
                return 1;
            else
                return this.checkedVal.length;
        },
        showTreeLimt() {
            return this.$dataFields.showTreeLimt ? true : false
        },
        inputVal: {
            get() {
              return this.value
          },
          set(value) {
              this.$emit('update:label',value)
          }
        }
    },
    watch:{
        label(value) {
            let change = false;
            if(value)
                change = true;
            else {
                
                if(!this.useInput && !this.value ) {
                change = true;
              }
            }
            if(change) {
                this.inputVal = value;
                this.treeName = value;
                this.initParentHint();
            }
        },
        value(value) {
            if(!value && !this.useInput) {//->不是可编辑状态
                if(!this.label)
                    this.inputVal = null;
                this.treeName = null;
                this.initParentHint();
            }
            if (!value){
		          this.inputVal = null;
              this.checkedData.name = ''
            }
        },
    },
    mounted() {
        if(this.label!==undefined)
            this.inputVal = this.label;
        this.treeName = this.label;
        if( this.dataProps && Object.keys(this.dataProps).length != 0){
            this.treeProps = Object.assign(this.treeProps,this.dataProps)
        }
        this.initParentHint();
    },
    methods:{
        renderContent(h, {node, data, store}) {
            //icon-homeclose blue
            if (this.showTreeNodeIcon) {
                //法人单位1     二级单位3     内设机构2     机构分组4和其他
                let classText = [
                    "iconfont blue",
                    node.data.icon ? node.data.icon
                        : node.data[this.treeProps.isFalse] ? "icon-group red"
                        : node.level === 1 && this.treeProps.firstIcon ? this.treeProps.firstIcon
                            : node.data[this.treeProps.children] && node.data[this.treeProps.children].length > 0 && this.treeProps.parentIcon ? this.treeProps.parentIcon
                                : this.treeProps.childrenIcon ? this.treeProps.childrenIcon
                                    : this.treeProps.icon ? this.treeProps.icon
                                        : node.data.b001110 == '1' ? "icon-farendanwei blue"
                                            : node.data.b001110 == '2' ? "icon-jigou blue"
                                                : node.data.b001110 == '3' ? "icon-neishejigou blue"
                                                    : node.data.b001110 == '4' ? "icon-jigoufenzu blue" : "icon-jigoufenzu blue"
                ];
                if (node.data.b001135) {
                    return (
                        <div class="commonTreeNode destruction" title={node.label}>
                        <i class={classText}> </i>
                        <span class="nodeName"> {node.label}</span>
                        </div>
                );
                } else {
                    return (
                        <div class="commonTreeNode" title={node.label}>
                        <i class={classText}> </i>
                        <span class="nodeName"> {node.label}</span>
                        </div>
                );
                }
            } else {
                if (this.render)
                    return this.render(h, {node, data, store});
                let classText = [
                    "iconfont blue",
                    node.data.icon ? node.data.icon
                        : node.data[this.treeProps.isFalse] ? "icon-group red"
                        : node.level === 1 && this.treeProps.firstIcon ? this.treeProps.firstIcon
                            : node.data[this.treeProps.children] && node.data[this.treeProps.children].length > 0 && this.treeProps.parentIcon ? this.treeProps.parentIcon
                                : this.treeProps.childrenIcon ? this.treeProps.childrenIcon
                                    : this.treeProps.icon ? this.treeProps.icon
                                        : node.data.orgCategory == '1' ? "icon-danwei blue"
                                            : node.data.orgCategory == '2' ? "icon-a-iconjiguandanwei blue"
                                                : node.data.orgCategory == '3' ? "icon-grouping yellow"
                                                    : node.data.orgCategory == '4' ? "icon-jigoufenzu blue" : "icon-jigoufenzu blue"
                    // :node.level === 1 ? "icon-homeclose blue" : "icon-homeopen blue"
                ];
                return (
                    <div class="commonTreeNode" title={node.label}>
                    <i class={classText}> </i>
                    <span class="nodeName"> {node.label}</span>
                    <span v-show={this.showText} style='padding-right:20px'> >>{data.b01001}</span>

                    </div>
            );
                //{this.$route.name == 'CadreManager' ? <span class="cadre-number">（{data.cadreCount ? data.cadreCount : 0}）</span> : ''}
            }
        },
        //选择展开弹窗
        searchClick(blur) {
            let type = this.$getType(this.value);
            this.isLazy = true;
            if(this.multiple) {
                if(this.value) {
                    this.checkedVal =  type==="array"?this.value:this.value.split(",");
                }else
                    this.checkedVal = [];
            }else{
                this.checkedVal = this.value;
            }
            this.searchData.organizationId = type==="array"?this.value.join(","):this.value;
            this.searchText = blur?this.inputVal:""; 
            this.treeData = new Array();
            if(!blur)
                this.dialogVisible = true;
        },
        //关键字搜索
        search(callback) {
            if(!this.searchText) {
                let treeNode = this.$refs.commonTree;
                treeNode.loadNode(treeNode.firstNode,treeNode.firstCallback);
                return;
            }
            let ajaxOptions = {
                data:{
                    name:this.searchText,
                },
                url:this.$baseUrl + "organization/findOrganizationByName?",
            };
            if(this.showTreeLimt) {
                ajaxOptions.data.permission = this.limit == 'unLimit' ? 0 : 1
            } else {
                delete ajaxOptions.data.permission
            }
            this.$ajaxPost(ajaxOptions,true,(res)=> {
                if(res.code === 200){
                    let treeData = res.data.map((item)=>{
                        item[this.treeProps.isLeaf] = true;
                        return item;
                    })
                    this.treeData = treeData;
                    this.checkedVal = this.value;
                    if(callback)
                        callback();

                }else{
                    this.$showMsg("error",res.message);
                }
            })
        },
        //input失去焦点
        blur() {
            if(!this.useInput || !this.openAfterBlur)
                return;
            if(this.inputVal!==this.treeName) {
                this.checkedData = null;
                this.checkedVal = null;
                this.save();
            }
            setTimeout(()=> {
                this.treeData = new Array();
                if(this.inputVal) {
                    this.searchClick(true);
                    this.search(()=>{
                        if(this.treeData.length>0) {
                            this.isLazy = false;
                            this.dialogVisible = true;
                        }
                        else{
                            this.checkedData = null;
                            this.checkedVal = null;
                            this.save();
                        }
                    });
                }else{
                    this.searchClick();
                }
            },10)
        },
        loadForNode(node, callback) {
            if(node.level>0) {
                this.nodeUrl = this.$baseUrl + 'organization/findOrganizationByParentId?parentId=' + node.data.id;
            }else{
                if(this.showTreeLimt) {
                    if(this.limit == 'limited') {
                        this.searchData.noPermission = false
                    } else if(this.limit == 'unLimit') {
                        this.searchData.noPermission = true
                    }
                } else {
                    delete this.searchData.noPermission
                }
                if(this.organizationType) {
                    this.searchData.noPermission = true;
                }
                this.nodeUrl = this.$baseUrl + 'organization/lstTreeNode';
            }
            callback();
        },
        nodeClick(val,data) {
            if(this.selectable)
                return;
            this.checkedVal = val;
            this.checkedData = data;
        },
        checkedChange(data,checkedData,checkedNode) {
            this.checkedVal = checkedData;
            if(this.multiple)
                this.checkedData = checkedNode;
            else
                this.checkedData = data;
        },
        save() {
            if(this.checkedData) {
                if(this.multiple)
                    this.inputVal = this.checkedData?this.checkedData.map(item=>item[this.treeProps.label]).join(","):null;
                else {
                    this.inputVal = this.checkedData?this.checkedData[this.treeProps.label]:null;
                }
            }else{
                if(this.isClear) {
                    this.inputVal = null;
                     this.isClear = false;//清空操作
                }
            }
            if(this.rule)
                this.$validate.validRule(this.rule, this.inputVal);
            this.$emit("input",this.checkedVal);
            this.$emit("update:label",this.inputVal);
            this.$emit("update:name",this.inputVal);
            this.$emit("save",this.checkedVal,this.checkedData);
            this.dialogVisible = false;
        },
        //清空
        clear() {
            this.checkedVal = null;
            this.checkedData = new Array();
            this.$refs.commonTree.lazyData = new Array();
            this.isClear = true;
        },

      initParentHint() {
            setTimeout(()=> {
                if(this.$parent.hint) {
                    let oldOrgName = this.$parent.hint.replace("原：","");
                    if(oldOrgName === this.inputVal || !oldOrgName || ~ this.$parent.hint.indexOf("undefined")||~this.$parent.hint.indexOf("null"))
                        this.$parent.showHint = false;
                    else
                        this.$parent.showHint = true;
                }
                if(this.inputVal) {//->是否选中代码
                    if(this.checkedVal || this.value)
                        this.$parent.warning = "";
                    else
                        this.$parent.warning = "未选中代码"
                }else
                    this.$parent.warning = "";
            },100)
        }
    },
}
</script>
<style lang="scss">
</style>
